package xin.petstore.framework.filter;


import com.eloancn.common.constant.Constant;
import com.eloancn.common.utils.IPUtils;
import com.eloancn.framework.cas.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by lijing on 2016/5/27.
 */
public class UserActionLogFilter implements Filter {

    private  final Logger logger = LoggerFactory.getLogger(UserActionLogFilter.class);
    private  String info="{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String uid=SessionUtils.getUserId()!=null?SessionUtils.getUserId():"";
        String localIP = IPUtils.getLocalIP();
        String userIP = IPUtils.getIpAddr(req);
        String agent = req.getHeader("user-agent");
        String requestUrl = req.getRequestURL().toString();
        String referer = req.getHeader("REFERER")==null?"":req.getHeader("REFERER");
        String requestType = req.getMethod();
        long startTime=System.currentTimeMillis();
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            long executeTime=System.currentTimeMillis()-startTime;
            if(logger.isErrorEnabled()){
                //TODO  此处的APPID需要修改
                logger.error(info,Constant.APPID_SITE , Constant.SERVICE_USER_ACTION, uid, localIP, userIP, agent,
                        session.getId(), System.currentTimeMillis(), executeTime, requestUrl, requestType, referer);
            }

        }
    }

    @Override
    public void destroy() {

    }
}
